import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FormBuilderService } from 'src/components/utils/form-builder.service';
import { ObjectFieldSchemaSection } from 'src/components/utils/json-schema';
import { JsonSchemaService } from 'src/components/utils/json-schema.service';
import { FlowGraphService } from '../flow-graph.service';
import { IAlgoUnit } from '../models';

@Component({
  selector: 'app-flow-graph',
  templateUrl: './flow-graph.component.html',
  styleUrl: './flow-graph.component.scss'
})
export class FlowGraphComponent implements OnInit {
  items: IAlgoUnit[] = [];
  cols: Column[] = [
    { field: 'name', header: 'Name' },
    { field: 'type', header: 'Type' },
    { field: 'color', header: 'Color' },
  ];

  current: IAlgoUnit | null = null;

  formGroup?: FormGroup;
  schema?: ObjectFieldSchemaSection;

  editorOptions = {
    theme: 'vs-dark',
    language: 'json'
  };

  get schemaJson() {
    return JSON.stringify(this.schema, null, 2);
  }
  set schemaJson(value: string) {
    try {
      this.schema = JSON.parse(value);
    }
    catch (Error) {
    }
  }

  constructor(private service: FlowGraphService,
    private schemaService: JsonSchemaService,
    private formService: FormBuilderService
  ) { }

  ngOnInit(): void {
    this.items = this.service.getList();
  }

  onGenerateSchema() {
    if (this.current) {
      const schema = <ObjectFieldSchemaSection>this.schemaService.Schema("IAlgoUnit", this.current!);
      this.schema = schema;
      console.log(schema);
    }
  }
  onGenerateFormGroup() {
    if (this.schema) {
      this.formGroup = this.formService.buildForm(this.schema!);
      this.formGroup.setValue(this.current!);
    }

  }

  onSelectionChange(e: IAlgoUnit) {
    this.formGroup?.setValue(e);
    this.onGenerateSchema();
    this.onGenerateFormGroup();
  }

  onUpdateCurrentValue() {
    this.current = this.formGroup?.value;
  }

  onModelChange(e: any) {
    console.log(e);
  }
}

interface Column {
  field: string;
  header: string;
}